
import 'package:easy_refresh/easy_refresh.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:im_app/im/util/DbUtil.dart';

import '../../dao/ImDepartmentDao.dart';
import '../../dao/ImUserDao.dart';
import '../../pojo/Enums.dart';
import '../../pojo/ImPojo.dart';
import '../view/model/DataChangeListener.dart';
import 'CommonModel.dart';

final class DepartmentListModel {

  final DataChangeStateListener<StatefulWidget, DepartmentTreeNode> departmentDataChangeListener;

  DepartmentListModel(this.departmentDataChangeListener) {
    // departmentDataChangeListener.dataList.add(DepartmentTreeModel(department: ImDepartment(currentUserId: 'root',
    //     code: 'root')));
  }

  int _pageStart = 0;
  final _pageSize = 10;

  Future<List<DepartmentTreeNode>> loadData() async {
    final departmentDao = ImDepartmentDao();
    _pageStart = 0;
    final departments = await departmentDao.getAll();
    List<ImDepartment> treeDepartments = _buildTree(departments);
    final models = treeDepartments.map((department) =>
        DepartmentTreeNode(department: department, children:
        DepartmentTreeNode.buildChildren(department.children))).toList();
    return models;
  }

  Future<List<DepartmentTreeNode>> loadMoreData(DepartmentTreeNode model) async {
    final userDao = ImUserDao();
    this._pageStart = model.children.length;
    final users = await userDao.getByDepartmentId(model.department!.code, _pageStart, _pageSize);
    print("more users ${users.length}");
    if (users.isEmpty) {
      return [];
    }
    final models = users.map((user) => DepartmentTreeNode(user: user)).toList();
    return models;
  }

  List<ImDepartment> _buildTree(List<ImDepartment> departments) {
    List<ImDepartment> roots = <ImDepartment>[];
    Map<String, ImDepartment> departmentMap = Map.fromIterable(departments, key: (department)=>department.code, value: (department)=>department);
    for (var department in departments) {
      if (department.parentCode == null) {
        roots.add(department);
      } else {
        ImDepartment parent = departmentMap[department.parentCode!]!;
        parent.children.add(department);
      }
    }
    return roots;
  }
}

final class DepartmentListState extends Equatable {
  final LoadingState state;
  final List<DepartmentTreeNode> models;

  const DepartmentListState._({
    this.state = LoadingState.loading,
    this.models = const <DepartmentTreeNode>[],
  });

  const DepartmentListState.loading() : this._();

  const DepartmentListState.success(List<DepartmentTreeNode> models)
      : this._(state: LoadingState.success,
      models: models);

  const DepartmentListState.failure() : this._(state: LoadingState.failure);

  @override
  List<Object?> get props => [state, models];
}


